import { createRouter, createWebHashHistory } from 'vue-router'
import store from '../store'
import ajax from '@/common/axios-core'
import Layout from '@/layout/index.vue'
import page from './router.config'
const pageModules = import.meta.glob("../views/**/**{.vue,index.js}")

const dontLoginPage = ['/login', '/tokenLogin', '/404', '/forget', '/Nologin', '/pay', '/fastPanel', '/mails/viewEmail'];
const routes = [
    // 基础路由
    {
        path: '/',
        redirect: '/admin/home'
    },
    {
        name: 'login',
        path: '/login',
        meta: {
            title: '登录'
        },
        component: () => import('@/views/Login.vue')
    },
    {
        name: 'admin',
        path: '/admin',
        component: Layout,
        children: page,
    },
    {
        name: '404',
        path: '/404',
        meta: {
            title: '页面不存在'
        },
        component: () => import('@/views/404.vue')
    }
]
const router = createRouter({
    history: createWebHashHistory(),
    routes
})
let loadingtime = 0


router.beforeEach(async (to, from, next) => {
    if (to.name === '404') {
        console.warn(`Navigated to 404 page. The original path was: `, from, to);
    }
    loadingtime++
    if (dontLoginPage.indexOf(to.path) >= 0) {
        document.title = to.meta.title;
        next()
    } else {
        if (to.path != '/login') {
            const token = store.state.userInfo?.token;
            if (token) {
                if (store.state.menuReged) {
                    next()
                } else {
                    console.log('动态添加路由')
                    const { menuList, actionList } = await ajax.getPermissionList();
                    store.dispatch("saveData", {
                        field: 'menuList',
                        value: menuList,
                        keep: true,
                        scope: 'system',
                    });
                    store.dispatch("saveData", {
                        field: 'actionList',
                        value: actionList,
                        keep: true,
                        scope: 'system',
                    });
                    // 使用parse函数递归注册所有菜单路由（包括子路由）
                    parse(menuList);
                    store.dispatch('saveData', { field: 'menuReged', value: true });
                    next({
                        path: to.path,
                        query: to.query,
                        replace: true
                    });
                }
            } else {
                router.push("/login");
                next(false);
            }
        } else {
            next({ path: '/404', replace: true })
        }
    }
})


/**
 * 解析缓存内的菜单数据进行路由注册
 * @param {*} list
 */
let parse = (list) => {
    console.log(list)
    list.forEach((item, k) => {
        regRoute(item)
        if (item.children?.length > 0) {
            parse(item.children);
        }
    })
}

/**
 * 注册一个路由
 * @param Object 要注册的路由信息
 */
function regRoute(menu) {
    if (menu.path) {
        if (router.hasRoute(menu.name)) {
            console.warn(`路由${menu.name}已存在,请勿重复注册。异常路由信息：`, menu)
            return
        }
        // if (menu.redirect) {
        //     // 注册降级路由重定向
        //     router.addRoute('admin', {
        //         path: menu.path.split('?')[0],
        //         redirect: menu.redirect
        //     })
        //     return
        // }
        router.addRoute('admin', {
            name: menu.name,
            path: menu.path.split('?')[0],
            component: getPageComponent(menu.component),
            meta: {
                title: menu.menuName,
                id: menu._id,
            }
        });
    }
}
// 根据node内置优先顺序规则加载组件
function getPageComponent(path) {
    return pageModules['../views/' + path + '.vue'] ||
        pageModules['../views/' + path] ||
        pageModules['../views/' + path + '.js'] ||
        pageModules['../views/' + path + '/index.js'] ||
        pageModules['../views/' + path + '/index.vue'] ||
        (() => import(/* @vite-ignore */'../views' + path))
}




export default router